package com.dwxt.cdms.admin.controller;


import com.dwxt.cdms.admin.service.UserServiceAdmin;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.entity.AdminUser;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.Role;
import com.dwxt.cdms.entity.dto.AdminUserDTO;
import com.dwxt.cdms.entity.vo.MenuVO;
import com.dwxt.cdms.service.CustomerService;
import com.dwxt.cdms.util.RandomValidateCodeUtil;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.common.annotation.ValidateFiled;
import com.dwxt.common.annotation.ValidateGroup;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.JwtUtils;
import com.dwxt.common.util.PartyUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/cdms/user")
@RestController
@Slf4j
public class UserControllerAdmin {

    @Autowired
    private UserServiceAdmin userServiceAdmin;

    @Autowired
    private CustomerService customerService;

    private final static Logger logger = LoggerFactory.getLogger(UserControllerAdmin.class);

    /**
     * @Description: 生成验证码
     * @param request:
     * @param response:
     * @return void
     * @author chendq
     * @date 2021/8/24
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>>   ", e);
        }
    }

    /**
     * showdoc
     *
     * @param phone    必选 string 手机号码
     * @param password 必选 string 密码
     * @param type     必选 int 用户类型(MALL:1,ENVIRONMENTAL_PROTECTION:2,RACE:3,ADMIN:4,MALL_ADMIN:5,MALL_TRAIN:6)
     * @return {"status":200,"msg":"SUCCESS","data":"eyJhbGciOiJIUzI1NiJ9.eyJzdGEiOjE1NzgzNjQ1MTExMTMsImV4cCI6MTU3ODM2ODExMTExMywidXNlcklkIjoyfQ.agKijFxhKrqG69d7Xw0l2i3JGNi22ZNOL6y_TPQf4b8"}
     * @catalog 后台公共部分管理/用户管理
     * @title 用户登录
     * @description 用户登录
     * @method post
     * @url /admin/user/login
     */
    @PostMapping("/login")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, filedName = "phone", notNull = true),
            @ValidateFiled(index = 0, filedName = "password", notNull = true),
    })
    public BaseResult login(AdminUser adminUser,HttpSession session) {
        //校验验证码
        boolean checkVerify = this.checkVerify(adminUser.getVerify(), session);
        if (!checkVerify) {
            return BaseResult.build(StatusCode.CODE_ERROR);
        }
        //校验账号密码
        AdminUser user = userServiceAdmin.login(adminUser.getPhone(), adminUser.getPassword());
        if (user != null) {
            String token = JwtUtils.createJWT(user.getId() + ",back", (long) 60 * 24 * 60 * 60 * 1000);
            return BaseResult.ok(token);
        } else {
            return BaseResult.build(StatusCode.USERNAME_PASSWORD_WRONG);
        }
    }

    public boolean checkVerify( String verifyInput, HttpSession session) {
        try{
            //从session中获取随机数
            String inputStr = verifyInput;
            String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            if (random == null) {
                return false;
            }
            if (random.equals(inputStr)) {
                return true;
            } else {
                return false;
            }
        }catch (Exception e){
            logger.error("验证码校验失败", e);
            return false;
        }
    }

    /**
     * 创建或修改带角色的用户
     *
     * @param adminUserDTO
     * @return
     */
    @RequestMapping("/createOrUpdateUser")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, filedName = "phone", regStr = "^[0-9]*$"),
            //@ValidateFiled(index = 0, filedName = "roleIds", notNull = true),
    })
    public BaseResult createOrUpdateUser(AdminUserDTO adminUserDTO) {
        return userServiceAdmin.createOrUpdateUser(adminUserDTO);
        //return BaseResult.ok();
    }


    /**
     * 返回带角色的用户
     *
     * @param pageSize
     * @param pageNum
     * @return
     */
    @RequestMapping("/pageList")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, notNull = true),
            @ValidateFiled(index = 1, notNull = true)
    })
    public BaseResult pageList(Integer pageSize, Integer pageNum,String name,String phone) {
        return userServiceAdmin.selectAllUserVo(pageSize,pageNum,name,phone);
    }


    @DeleteMapping("/delete")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, notNull = true)
    })
    public BaseResult delete(Integer[] id) {
        int i = userServiceAdmin.batchDeleteById(id);
        return i == 0 ? BaseResult.build(StatusCode.USER_NOT_EXIST) : BaseResult.ok();
    }

    @RequestMapping("/disOrEnable")
    public BaseResult disOrEnable(Integer id) {
        userServiceAdmin.disOrEnable(id);
        return BaseResult.ok();
    }

    /**
     * 获取用户拥有权限的菜单
     *
     * @return
     */
    @RequestMapping("/menuList")
    public BaseResult menuList() {
        String userId = PartyUtil.getCurrentUserId();
        List<MenuVO> menuVOS = userServiceAdmin.menuList(Integer.parseInt(userId));
        if (menuVOS.size() == 0) {
            log.error("没有权限");
            return BaseResult.build(StatusCode.PERMISSION_FAIL);
        }
        return BaseResult.ok(menuVOS);
    }


    @RequestMapping("/menuIdList")
    public BaseResult menuIdList() {
        String userId = PartyUtil.getCurrentUserId();
        List<Integer> menuVOS = userServiceAdmin.menuIdList(Integer.parseInt(userId));
        if (menuVOS.size() == 0) {
            log.error("没有权限");
            return BaseResult.build(StatusCode.PERMISSION_FAIL);
        }
        return BaseResult.ok(menuVOS);
    }

    @RequestMapping("/selectRoles")
    public BaseResult selectRoles() {
        List<Role> roleList = userServiceAdmin.selectRolesByUserId(PartyUtil.getCurrentUserId());
        return BaseResult.ok(roleList);
    }


    @RequestMapping("/selectUser")
    public BaseResult selectUser() throws InterruptedException {
        //Thread.sleep(20 * 1000);
        AdminUser adminUser = userServiceAdmin.selectUser();
        return BaseResult.ok(adminUser);
    }

    @RequestMapping("/selectUserById")
    public BaseResult selectUserById(Integer id) {
        AdminUser user = userServiceAdmin.selectUserById(id);
        return BaseResult.ok(user);
    }

    /**
    * @Description: TV端微信扫描登录
    * @Param [phone]
    * @Return com.dwxt.common.base.BaseResult
    * @Author chendq
    * @Date 2021/12/8
    **/
    @RequestMapping("/wxLogin")
    public BaseResult wxLogin(String scene) throws ParseException {
        //校验手机号
        String phone = RedisUtil.get(scene, String.class);
        if (StringUtil.isNotBlank(phone)) {
            Customer customer = customerService.selectCustomerByPhone(phone);
            if (customer == null) {
                customer = customerService.selectOrInsert(phone);
            }
            if (customer != null) {
                String token = JwtUtils.createJWT(customer.getId() + ",back", (long) 60 * 24 * 60 * 60 * 1000);
                HashMap<String, Object> map = new HashMap<>();
                Customer customerInfo = customerService.selectCustomerByPhone(phone);
                map.put("phone", phone);
                map.put("Authorization", token);
                map.put("customerInfo", customerInfo);
                return BaseResult.ok(map);
            } else {
                return BaseResult.build(StatusCode.USERNAME_PASSWORD_WRONG);
            }
        }
        return BaseResult.build(StatusCode.NO_ALLOW_LOGIN);
    }

    /***
    * @Description: TV端发送验证码
    * @Param [phone]
    * @Return com.dwxt.common.base.BaseResult
    * @Author chendq
    * @Date 2021/12/7
    **/
    @RequestMapping("/sendCode")
    public BaseResult sendCode(String phone) {
        return userServiceAdmin.sendCode(phone);
    }

    /**
    * @Description: TV端验证码登录
    * @Param [adminUser]
    * @Return com.dwxt.common.base.BaseResult
    * @Author chendq
    * @Date 2021/12/8
    **/
    @PostMapping("/codeLogin")
    public BaseResult codeLogin(AdminUser adminUser) throws ParseException {
        String loginCode = adminUser.getCode();
        if (StringUtil.isBlank(adminUser.getPhone())) {
            return BaseResult.build(StatusCode.USERNAME_INVALID);
        }
        if (StringUtil.isBlank(loginCode)) {
            return BaseResult.build(StatusCode.CODE_ERROR);
        }
        //校验验证码
        String phone = adminUser.getPhone();
        String code = RedisUtil.get(phone, String.class);
        //验证码匹配
        if (loginCode.equals(code)) {
            Customer customer = customerService.selectCustomerByPhone(adminUser.getPhone());
            String token = JwtUtils.createJWT(customer.getId() + ",back", (long) 60 * 24 * 60 * 60 * 1000);
            return BaseResult.ok(token);
        }
        return BaseResult.build(StatusCode.CODE_ERROR);
    }

}